package dao

import (
	"goblog/models"
	"github.com/astaxie/beego/orm"
	"fmt"
	"github.com/astaxie/beego"
)

type ArticleDao struct {
	Dao orm.Ormer
}

const (
	DISPLAY = "display"
	HIDE    = "hide"
)

type ArticleTerm struct {
	models.Term
	FirstId  int `json:"first_id"`
	SecondId int `json:"second_id"`
	ThirdId  int `json:"third_id"`
	Title    string `json:"title"`
	Status   string `json:"status"`
}

func (this *ArticleDao) Get(id int) models.Article {
	if this.Dao == nil {
		this.Dao = orm.NewOrm()
	}
	var article models.Article
	this.Dao.Raw("select id, first_cid, second_cid, third_cid, title, tags, summary, "+
		"content, status, img_url, author, comments, views, url, updated, created from article where id=?", id).QueryRow(&article)
	return article
}

func (this *ArticleDao) Save(article *models.Article) {
	if this.Dao == nil {
		this.Dao = orm.NewOrm()
	}
	r, err := this.Dao.Raw(`insert into article(id, first_cid, second_cid, third_cid, title, tags, summary,
		content, status, img_url, author, comments, views, url, updated, created)
		values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, article.Id, article.FirstCid, article.SecondCid, article.ThirdCid,
		article.Title, article.Tags, article.Summary, article.Content, article.Status, article.ImgUrl,
		article.Author, article.Comments, article.Views, "", article.Updated, article.Created).Exec()
	if err != nil {
		beego.Error(err)
	} else {
		id, _ := r.LastInsertId()
		article.Id = int(id)
	}
}

func (this *ArticleDao) PlusViews(id int) {
	this.Dao.Raw("update article set views = views + 1 where id=?", id).Exec();
}

func (this *ArticleDao) Find(term *ArticleTerm) {
	if this.Dao == nil {
		this.Dao = orm.NewOrm()
	}
	var args []interface{}
	var articles []models.Article
	sql := "select id, first_cid, second_cid, third_cid, title, tags, summary, " +
		"content, status, img_url, author, comments, views, url, updated, created from article where 1=1"
	if term.FirstId != 0 {
		sql += " and first_cid=?"
		args = append(args, term.FirstId)
	}
	if term.SecondId != 0 {
		sql += " and second_cid=?"
		args = append(args, term.SecondId)
	}
	if term.ThirdId != 0 {
		sql += " and third_cid=?"
		args = append(args, term.ThirdId)
	}
	if len(term.Status) != 0 {
		sql += " and status=?"
		args = append(args, term.Status)
	}
	if len(term.Title) != 0 {
		sql += " and title like ?"
		args = append(args, "%"+term.Title+"%")
	}

	id, err := Paging(sql, args, &term.Term, this.Dao).QueryRows(&articles)
	if err != nil {
		panic(err)
		fmt.Println(id)
	}
	term.Data = articles
}
